package com.tim.app.ui.fragment.found;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.application.library.base.BaseFragment;
import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.widget.EmptyLayout;
import com.application.library.widget.loadmore.LoadMoreContainer;
import com.application.library.widget.loadmore.LoadMoreHandler;
import com.application.library.widget.loadmore.LoadMoreRecycleViewContainer;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.server.api.API_Discover;
import com.tim.app.server.entry.MusicAlbum;
import com.tim.app.server.entry.Story;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.server.result.StoryListResult;
import com.tim.app.ui.activity.StoryDetailActivity;
import com.tim.app.ui.adapter.found.StoryAdapter;
import com.tim.app.ui.view.MusicAlbumDetialHeadView;
import com.tim.app.util.ToastUtil;

import java.util.ArrayList;

/**
 * 专辑节目单列表页面
 */
public class MusicAlbumProgramFragment extends BaseFragment implements LoadMoreHandler, BaseRecyclerAdapter.OnItemClickListener {

    public static final String TAG = "MusicAlbumProgramFragment";
    private View rootView;
    private LoadMoreRecycleViewContainer load_more;
    private WrapRecyclerView wrvStory;
    private StoryAdapter adapter;
    private ArrayList<Story> dataList;

    private MusicAlbumDetialHeadView headView;
    private EmptyLayout emptyLayout;

    boolean isOrderByReverse = true;
    private MusicAlbum musicAlbum;


    public static MusicAlbumProgramFragment newInstance(MusicAlbum musicAlbum) {
        MusicAlbumProgramFragment newFragment = new MusicAlbumProgramFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("musicAlbum", musicAlbum);
        newFragment.setArguments(bundle);
        return newFragment;
    }

    public void updateData(MusicAlbum musicAlbum) {
        this.musicAlbum = musicAlbum;
        if (musicAlbum.getIsOffice() != 1) {
            adapter.setShowSelf(false);
            adapter.setImage(musicAlbum.getImage());
            adapter.notifyDataSetChanged();
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == rootView) {
            rootView = inflater.inflate(R.layout.fragment_story, container, false);

            load_more = (LoadMoreRecycleViewContainer) rootView.findViewById(R.id.load_more);
            wrvStory = (WrapRecyclerView) rootView.findViewById(R.id.wrvStory);
            wrvStory.setOverScrollMode(View.OVER_SCROLL_NEVER);

            load_more.useDefaultFooter(View.GONE);
            load_more.setAutoLoadMore(true);
            load_more.setLoadMoreHandler(this);

            dataList = new ArrayList<>();
            adapter = new StoryAdapter(getContext(), dataList);
            adapter.updateData(dataList);

            emptyLayout = new EmptyLayout(getActivity(), load_more);
            emptyLayout.showLoading();
            emptyLayout.setEmptyButtonClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    emptyLayout.showLoading();
                    initData();
                }
            });

            headView = (MusicAlbumDetialHeadView) LayoutInflater.from(getActivity()).inflate(R.layout.music_album_detail_head_view, null);

            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            wrvStory.addHeaderView(headView);
            wrvStory.setLayoutManager(layoutManager);
            dataList = new ArrayList<>();
            adapter = new StoryAdapter(getActivity(), dataList);
            wrvStory.setAdapter(adapter);
            adapter.setOnItemClickListener(this);
            Bundle args = getArguments();
            if (args != null) {
                if (args.containsKey("musicAlbum")) {
                    musicAlbum = (MusicAlbum) args.getSerializable("musicAlbum");
                    updateData(musicAlbum);
                }
            }
            initData();
            EventManager.ins().registListener(EventTag.ORDER_BY_ALBUM_TIME, eventListener);
            EventManager.ins().registListener(EventTag.ORDER_BT_ALBUM_HOT, eventListener);
        }
        return rootView;
    }

    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                if (dataList != null) {
                    dataList.clear();
                }
                StoryListResult result = new Gson().fromJson(resultValue, StoryListResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        adapter.notifyDataSetChanged();
                        headView.setData(result.getTotal());
                    }
                    pageNum = result.getRes().getArraylist().getCurrentPageNo();
                    if (pageNum != result.getRes().getArraylist().getTotalPageCount()) {
                        load_more.loadMoreFinish(false, true);
                    } else {
                        load_more.loadMoreFinish(false, false);
                    }
                }

                if (dataList == null || dataList.size() == 0) {
                    emptyLayout.showEmpty();
                } else {
                    emptyLayout.showContent();
                }
            } else {
                emptyLayout.showEmptyOrError(errCode);
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    StringResponseCallback moreCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                StoryListResult result = new Gson().fromJson(resultValue, StoryListResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        adapter.notifyDataSetChanged();
                    }
                    pageNum = result.getRes().getArraylist().getCurrentPageNo();
                    if (pageNum != result.getRes().getArraylist().getTotalPageCount()) {
                        load_more.loadMoreFinish(false, true);
                    } else {
                        load_more.loadMoreFinish(false, false);
                    }
                }
            } else {
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.ORDER_BY_ALBUM_TIME:
                    isOrderByReverse = true;
                    initData();
                    break;
                case EventTag.ORDER_BT_ALBUM_HOT:
                    isOrderByReverse = false;
                    initData();
                    break;
            }
        }
    };

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != rootView && null != rootView.getParent()) {
            ((ViewGroup) rootView.getParent()).removeView(rootView);
        }
        EventManager.ins().removeListener(EventTag.ORDER_BY_ALBUM_TIME, eventListener);
        EventManager.ins().removeListener(EventTag.ORDER_BT_ALBUM_HOT, eventListener);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(TAG);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


    int pageNum = 1;//页码

    private void initData() {
        pageNum = 1;
        if (isOrderByReverse) {
            API_Discover.ins().getMusicAlbumDataList(TAG, musicAlbum.getId(), AppKey.ORDER_BY_REVERSE, pageNum, AppKey.PAGE_SIZE, refreshCallback);
        } else {
            API_Discover.ins().getMusicAlbumDataList(TAG, musicAlbum.getId(), AppKey.ORDER_BY_SEQUENCE, pageNum, AppKey.PAGE_SIZE, refreshCallback);
        }
    }

    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        if (isOrderByReverse) {
            API_Discover.ins().getMusicAlbumDataList(TAG, musicAlbum.getId(), AppKey.ORDER_BY_REVERSE, pageNum + 1, AppKey.PAGE_SIZE, moreCallback);
        } else {
            API_Discover.ins().getMusicAlbumDataList(TAG, musicAlbum.getId(), AppKey.ORDER_BY_SEQUENCE, pageNum + 1, AppKey.PAGE_SIZE, moreCallback);
        }
    }

    @Override
    public void onItemClick(View view, int position, long id) {
        StoryDetailActivity.start(getContext(), dataList, position, false);
    }
}
